package com.lex.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lex.common.api.CommonResult;
import com.lex.common.api.IdUtil;
import com.lex.data.admin.mapper.LexCmsUserRoleMapper;
import com.lex.data.admin.mapper.LexCmsUsersMapper;
import com.lex.data.admin.model.LexCmsUserRole;
import com.lex.data.admin.model.LexCmsUsers;
import com.lex.entity.account.AddUserDto;
import com.lex.entity.account.UserListVo;
import com.lex.entity.params.UsersQueryParams;
import com.lex.mapper.UserListMapper;
import com.lex.service.AccountService;
import com.lex.service.BaseService;
import com.lex.util.MyContext;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private LexCmsUsersMapper lexCmsUsersMapper;

    @Autowired
    private UserListMapper userListMapper;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private LexCmsUserRoleMapper userRoleMapper;

    @Autowired
    private BaseService baseService;
    /**
     * 获取所有用户列表，带分页
     * @param queryParamDto
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public CommonResult getUsersListByPage(UsersQueryParams queryParamDto, Integer page, Integer pageSize) {
        Page<UserListVo> userListVoPage = new Page<>(page, pageSize);
        List<UserListVo> userList = userListMapper.getUsersList(queryParamDto, userListVoPage);
        long total = userListVoPage.getTotal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("items", userList);
        return CommonResult.success(map);
    }

    /**
     * 判断用户名是否重复
     * @param userName
     * @return
     */
    @Override
    public CommonResult isUserNameExist(String userName) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("account", userName);
        long count = lexCmsUsersMapper.selectCount(queryWrapper);
        if (count > 0) {
            return CommonResult.failed("用户名已存在");
        }
        return CommonResult.success("用户名可用");
    }

    /**
     * 添加用户
     * @param addUserDto
     * @return
     */
    @Override
    @Transactional
    public CommonResult addUser(AddUserDto addUserDto) {
        //判断密码和确认密码是否一致
        if (!addUserDto.getPassword().equals(addUserDto.getConfirmPassword())) {
            return CommonResult.failed("密码和确认密码不一致");
        }
        //判断用户名是否重复
        if(isUserNameExist(addUserDto.getAccount()).getCode() == 500){
            return CommonResult.failed("用户名已存在");
        }
        //判断手机号是否重复
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone_num", addUserDto.getPhoneNum());
        long count = lexCmsUsersMapper.selectCount(queryWrapper);
        if (count > 0) {
            return CommonResult.failed("手机号已存在");
        }
        //判断邮箱是否重复
        queryWrapper.clear();
        queryWrapper.eq("email", addUserDto.getEmail());
        count = lexCmsUsersMapper.selectCount(queryWrapper);
        if (count > 0) {
            return CommonResult.failed("邮箱已存在");
        }
        LexCmsUsers lexCmsUsers = new LexCmsUsers();
        lexCmsUsers.setAccount(addUserDto.getAccount());
        lexCmsUsers.setAvatar(addUserDto.getAvatar());
        lexCmsUsers.setDeptId(addUserDto.getDept());
        lexCmsUsers.setEmail(addUserDto.getEmail());
        lexCmsUsers.setPhoneNum(addUserDto.getPhoneNum());
        IdUtil worker1 = new IdUtil(1, 1);
        lexCmsUsers.setUserId(worker1.nextId());
        //设置密码
        lexCmsUsers.setPassword(passwordEncoder.encode(addUserDto.getPassword()));
        int insert = lexCmsUsersMapper.insert(lexCmsUsers);
        //添加user_role
        LexCmsUserRole userRole = new LexCmsUserRole();
        userRole.setRoleId(addUserDto.getRole());
        userRole.setUserId(lexCmsUsers.getUserId());
        userRoleMapper.insert(userRole);
        return insert > 0
                ? CommonResult.success("添加用户成功！")
                : CommonResult.failed("添加用户失败！");
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public CommonResult deleteUser(Long userId) {
        //查询用户是否存在
        LexCmsUsers lexCmsUsers = lexCmsUsersMapper.selectOne(
                new QueryWrapper<LexCmsUsers>().eq("user_id", userId)
        );
        if (lexCmsUsers == null) {
            return CommonResult.failed("用户不存在");
        }
        //判断是否位主账号
        if (lexCmsUsers.getIsMain() == 1) {
            return CommonResult.failed("主账号不能删除");
        }
        //删除用户
        int delete = lexCmsUsersMapper.delete(new QueryWrapper<LexCmsUsers>().eq("user_id", userId));
        //删除用户角色关系
        userRoleMapper.delete(new QueryWrapper<LexCmsUserRole>().eq("user_id", userId));
        return delete > 0
                ? CommonResult.success("删除用户成功！")
                : CommonResult.failed("删除用户失败！");
    }

    /**
     *  修改用户
     * @param addUserDto
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateUser(AddUserDto addUserDto) {
        //判断密码和确认密码是否一致
        if (!addUserDto.getPassword().equals(addUserDto.getConfirmPassword())) {
            return CommonResult.failed("密码和确认密码不一致");
        }
        //查询用户
        LexCmsUsers lexCmsUsers = lexCmsUsersMapper.selectOne(
                new QueryWrapper<LexCmsUsers>().eq("user_id", addUserDto.getUserId())
        );
        if (lexCmsUsers == null) {
            return CommonResult.failed("用户不存在");
        }
        //判断用户名是否重复
        if (!lexCmsUsers.getAccount().equals(addUserDto.getAccount())) {
            if(isUserNameExist(addUserDto.getAccount()).getCode() == 500){
                return CommonResult.failed("用户名已存在");
            }
        }
        //判断手机号是否重复
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone_num", addUserDto.getPhoneNum());
        LexCmsUsers lexCmsUsers1 = lexCmsUsersMapper.selectOne(queryWrapper);
        if (lexCmsUsers1 != null && !lexCmsUsers1.getUserId().equals(addUserDto.getUserId())) {
            return CommonResult.failed("手机号已存在");
        }
        //判断邮箱是否重复
        queryWrapper.clear();
        queryWrapper.eq("email", addUserDto.getEmail());
        lexCmsUsers1 = lexCmsUsersMapper.selectOne(queryWrapper);
        if (lexCmsUsers1 != null && !lexCmsUsers1.getUserId().equals(addUserDto.getUserId())) {
            return CommonResult.failed("邮箱已存在");
        }
        lexCmsUsers.setAccount(addUserDto.getAccount());
        lexCmsUsers.setAvatar(addUserDto.getAvatar());
        lexCmsUsers.setDeptId(addUserDto.getDept());
        lexCmsUsers.setEmail(addUserDto.getEmail());
        lexCmsUsers.setPhoneNum(addUserDto.getPhoneNum());
        //设置密码,密码不为空的时候设置
        if (addUserDto.getPassword() != null && !addUserDto.getPassword().isEmpty()) {
            lexCmsUsers.setPassword(passwordEncoder.encode(addUserDto.getPassword()));
        }
        int update = lexCmsUsersMapper.update(lexCmsUsers,
                new QueryWrapper<LexCmsUsers>().eq("user_id", addUserDto.getUserId()));
        //修改user_role
        LexCmsUserRole userRole = userRoleMapper.selectOne(
                new QueryWrapper<LexCmsUserRole>().eq("user_id", addUserDto.getUserId())
        );
        userRole.setRoleId(addUserDto.getRole());
        userRoleMapper.update(userRole,
                new QueryWrapper<LexCmsUserRole>().eq("user_id", addUserDto.getUserId()));
        //删除用户缓存
        baseService.getCacheService().delUser(addUserDto.getAccount());
        return update > 0
                ? CommonResult.success("修改用户成功！")
                : CommonResult.failed("修改用户失败！");
    }

    /**
     * 修改用户密码
     * @param passwordOld
     * @param passwordNew
     * @return
     */
    @Override
    public CommonResult updateUserPassword(String passwordOld, String passwordNew) {
        //查询用户
        LexCmsUsers lexCmsUsers = lexCmsUsersMapper.selectOne(
                new QueryWrapper<LexCmsUsers>().eq("account", MyContext.getCurrentUserName())
        );
        if (lexCmsUsers == null) {
            return CommonResult.failed("用户不存在");
        }
        //判断旧密码是否正确
        if (!passwordEncoder.matches(passwordOld, lexCmsUsers.getPassword())) {
            return CommonResult.failed("旧密码错误");
        }
        lexCmsUsers.setPassword(passwordEncoder.encode(passwordNew));
        int update = lexCmsUsersMapper.update(lexCmsUsers,
                new QueryWrapper<LexCmsUsers>().eq("user_id", lexCmsUsers.getUserId()));
        //删除用户缓存
        baseService.getCacheService().delUser(lexCmsUsers.getAccount());
        return update > 0
                ? CommonResult.success("修改密码成功！")
                : CommonResult.failed("修改密码失败！");
    }

    /**
     * 修改用户状态
     * @param userId
     * @param status
     * @return
     */
    @Override
    public CommonResult updateUserStatus(Long userId, Byte status) {
        //修改用户状态
        LexCmsUsers lexCmsUsers = new LexCmsUsers();
        lexCmsUsers.setStatus(status);
        int update = lexCmsUsersMapper.update(lexCmsUsers,
                new QueryWrapper<LexCmsUsers>().eq("user_id", userId));
        //删除用户缓存
        baseService.getCacheService().delUser(lexCmsUsers.getAccount());
        return update > 0
                ? CommonResult.success("修改用户状态成功！")
                : CommonResult.failed("修改用户状态失败！");
    }
}
